<?php
/**
 * Created by PhpStorm.
 * User: tengwei
 * Date: 2018/11/16
 * Time: 10:06 AM
 */

namespace common\logics\bank;

use common\widgets\Request;
use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;

class BankLogic extends BaseObject implements IBank
{
    /** @var \common\sources\read\bank\BankAccess $RBankAccess */
    private $RBankAccess;
    /** @var \common\sources\write\bank\BankAccess $RBankAccess */
    private $WBankAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess */
    private $RBuyUserAccess;
    /** @var  \common\sources\read\message\MesgAccess  $RMesgAccess */
    private $RMesgAccess;
    /** @var \common\sources\write\message\MesgAccess  $WMesgAcdess */
    private $WMesgAcdess;
    /** @var \common\sources\read\classifyreason\ClassifyReasonAccess  $RClassifyReasonAccess ***/
    private $RClassifyReasonAccess;


    public function init()
    {
        $this->RBankAccess = Yii::$container->get('RBankAccess');
        $this->WBankAccess = Yii::$container->get('WBankAccess');
        $this->RBuyUserAccess = Yii::$container->get('RBuyUserAccess');
        $this->RMesgAccess = Yii::$container->get('RMesgAccess');
        $this->WMesgAcdess = Yii::$container->get('WMesgAccess');
        $this->RClassifyReasonAccess = Yii::$container->get("RClassifyReasonAccess");
        parent::init();
    }

    public function addBdBank($param)
    {
        if (empty($param['buy_id'])){
            return Tool::returnJson([],401,'买手id不能为空');
        }
        if (empty($param['real_name'])){
            $param['error_message'] = "姓名不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],402,'姓名不能为空');
        }
        if (empty($param['cardnum'])){
            $param['error_message'] = "银行卡号不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],403,'银行卡号不能为空');
        }
        if (empty($param['bankname'])){
            $param['error_message'] = "银行名不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],405,'银行名不能为空');
        }
        if(empty($param['pro_name'])){
            $param['error_message'] = "省名称不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],407,'省名称不能为空');
        }
        if(empty($param['pro_code'])){
            $param['error_message'] = "省代号不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],408,'省代号不能为空');
        }
        if(empty($param['city_name'])){
            $param['error_message'] = "市名称不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],409,'市名称不能为空');
        }
        if(empty($param['city_code'])){
            $param['error_message'] = "市代号不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],410,'市代号不能为空');
        }
        if (empty($param['bankbranch'])){
            $param['error_message'] = "开户支行名称不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],411,'开户支行名称不能为空');
        }
        if (empty($param['idcard'])){
            $param['error_message'] = "身份证号不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],412,'身份证号不能为空');
        }
        if (empty($param['bankphone'])){
            $param['error_message'] = "银行预留手机号不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],413,'银行预留手机号不能为空');
        }
        if (empty($param['verifycode'])){
            $param['error_message'] = "验证码不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],415,'验证码不能为空');
        }
        if(empty($param['id_positive_url']))
        {
            $param['error_message'] = "身份证正面不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],416,'身份证正面不能为空');
        }
        if(empty($param['id_verso_url']))
        {
            $param['error_message'] = "身份证反面不能为空";
            $this->bandDd($param);
            return Tool::returnJson([],417,'身份证反面不能为空');
        }

        $real_name = $param['real_name'];
        $idcard = $param['idcard'];
        $cardnum = $param['cardnum'];
        $bankphone = $param['bankphone'];
        $param['update_time'] = '';
        $param['create_time'] = time();
        //判断用户是否已经绑定过 如果绑定过  不让用户再次绑定
        $userBank = $this->RBankAccess->getBuyUserBankAccount($param['buy_id']);
        if(!empty($userBank)){
            $param['error_message'] = "该买手用户已经绑定体现银行卡，不能再次绑定";
            $this->bandDd($param);
            return Tool::returnJson([],418,'该买手用户已经绑定体现银行卡，不能再次绑定');
        }
        //短信验证码 校验
        $data['phone']=$param['bankphone'];
        $smsArr = $this->RMesgAccess->getVerifyCode($param['bankphone'],5);
        if (intval($smsArr['verifycode']) != (int)$param['verifycode']){
            $param['error_message'] = "验证码错误";
            $this->bandDd($param);
            return Tool::returnJson([],419,'验证码错误');
        }
        //组装四要素数组
//        $data = compact('real_name','idcard','cardnum','bankphone');
        $rescard = $this->cardAuth(['real_name'=> $real_name,"idcard"=>$idcard,"cardnum"=> $cardnum,"bankphone"=> $bankphone]);
        $resarr = json_decode($rescard, true);
        if($resarr['data']['result'] != '01'){
            $param['error_message'] =  $resarr['data']['remark'];
            $this->bandDd($param);
            return Tool::returnJson([],420, $resarr['data']['remark']);
        }
        if(!(strpos($resarr['data']['bankName'],$param['bankname']) !== false))
        {
            $param['error_message'] = "选择开户行与卡开户行不匹配";
            $this->bandDd($param);
            return Tool::returnJson([],421,'选择开户行与卡开户行不匹配');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if ($resarr['data']['result'] == '01') {
                $result = $this->WBankAccess->addBdBank($param);
                if(!$result){
                    $param['error_message'] = "银行卡信息存储失败";
                    $this->bandDd($param);
                    $transaction->rollBack();
                    return Tool::returnJson([],422,'银行卡信息存储失败');
                }
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson([],200,'绑定银行卡成功');
            }
            $transaction->rollBack();
            return Tool::returnJson([],423,'你输入的银行信息有误,请重新输入, 错误如：'.$resarr['data']['remark']);
        }catch (\Exception $e){
            $param['error_message'] = "绑定银行卡失败";
            $this->bandDd($param);
            $transaction->rollBack();
            return Tool::returnJson([],5000,'绑定银行卡失败'.$e->getMessage());
        };
    }
    //绑卡错误订单提醒
    private function bandDd($data)
    {
        $buyuser = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        $dd_url = Yii::$app->params['band_car_error_users'];
        $message = $buyuser['phone']."用户绑定提现信息失败,真实姓名:".$data['real_name'].",银行卡号为:".$data['cardnum'].",银行名:".$data['bankname'].",开户支行:".$data['bankbranch']
            .",身份证号为:".$data['idcard'].",银行预留手机号码为:".$data['bankphone'].",身份证正面:".$data['id_positive_url'].",身份证反面:".$data['id_verso_url'].",错误信息为:".$data['error_message'];

        $param = array ('msgtype' => 'text','text' => array ('content' => $message),"at"=>["isAtAll" =>true]);
        $data_string = json_encode($param);
        $this->request_by_curl($dd_url, $data_string);
    }

    //获取提现列表
    public function getReflectList($param)
    {
        if (empty($param['buy_id'])){
            return Tool::returnJson([],401,'买手id不能为空');
        }
        //用户
        $buyUser = $this->RBuyUserAccess->getBuyUserInfo($param['buy_id']);
        if(empty($buyUser)){
            return Tool::returnJson([],402,'买手用户不存在');
        }
        //获取绑定银行卡信息
        $buyUserBank = $this->RBankAccess->getBuyUserBankAccount($param['buy_id']);
        $arr = [];
        if(!empty($buyUserBank)){
            $banks = array(
                'real_name' => $buyUserBank['real_name'],
                'typename' => $buyUserBank['bankname'],
                'cardnum' => $buyUserBank['cardnum'],
                'status' => Yii::$app->params['audit_status'][$buyUserBank['status']]
            );
            $ids = array(
                'real_name' => $buyUserBank['real_name'],
                'typename' => '身份证',
                'cardnum' => $buyUserBank['idcard'],
                'status' => Yii::$app->params['audit_status'][$buyUserBank['status']],
                "id_positive_url" => $buyUserBank['id_positive_url'],
                "id_verso_url" => $buyUserBank['id_verso_url'],
            );
            $arr[0] = $banks;
            $arr[1] = $ids;
            //如果不通过显示不通过原因
            $reasons = '';
            if(!empty($buyUserBank['reason']))
            {
                $classifyreason = $this->RClassifyReasonAccess->getClassifyReasonByIds($buyUserBank['reason']);
                if(count($classifyreason) >0)
                {
                    $reasonArr = array_column($classifyreason,"reason");
                    $reasons = implode(',',$reasonArr);
                }
            }
            $arr[1]['reasons'] = $reasons;
        }

        return Tool::returnJson($arr, 200);
    }

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    public function modifyBank($param)
    {
        if(empty($param['b_id'])){
            return Tool::returnJson([],401,'提现绑定id不能为空');
        }
        if(empty($param['real_name'])){
            return Tool::returnJson([],402,'真实姓名不能为空');
        }
        if (empty($param['cardnum'])){
            return Tool::returnJson([],403,'银行卡号不能为空');
        }
        if(empty($param['bankname'])){
            return Tool::returnJson([],405,'银行名称不能为空');
        }
        if(empty($param['pro_name'])){
            return Tool::returnJson([],406,'省名称不能为空');
        }
        if(empty($param['pro_code'])){
            return Tool::returnJson([],407,'省代号不能为空');
        }
        if(empty($param['city_name'])){
            return Tool::returnJson([],408,'市名称不能为空');
        }
        if(empty($param['city_code'])){
            return Tool::returnJson([],409,'市代号不能为空');
        }
        if (empty($param['bankbranch'])){
            return Tool::returnJson([],410,'开户支行名称不能为空');
        }
        if(empty($param['idcard'])){
            return Tool::returnJson([],411,'身份证号不能为空');
        }
        if (empty($param['bankphone'])){
            return Tool::returnJson([],412,'银行预留手机号不能为空');
        }
        if (empty($param['verifycode'])){
            return Tool::returnJson([],413,'验证码不能为空');
        }
        if(empty($param['buy_id']))
        {
            return Tool::returnJson([],420,'买手id不能为空');
        }
        //判断该提现绑定是否绑定
        $buyUserBank = $this->RBankAccess->getBuyUserBankById($param['b_id']);
        if(empty($buyUserBank)){
            return Tool::returnJson([],415,'该提现绑定不存在,请重新输入');
        }
        //短信验证码 校验
        $data['phone']=$param['bankphone'];
        $smsArr = $this->RMesgAccess->getVerifyCode($param['bankphone'],5);
        if (intval($smsArr['verifycode']) !== intval($param['verifycode'])){
            return Tool::returnJson([],416,'验证码错误');
        }

        $real_name = $param['real_name'];
        $idcard = $param['idcard'];
        $cardnum = $param['cardnum'];
        $bankphone = $param['bankphone'];
        $param['update_time'] = time();

        //组装四要素数组
        $data = compact('real_name','idcard','cardnum','bankphone');
        $rescard = $this->cardAuth($data);
        $resarr = json_decode($rescard, true);

        if($resarr['code'] != 200000){
            return Tool::returnJson([],418, $resarr['message']);
        }
        if(!(strpos($resarr['data']['bankName'],$param['bankname']) !== false)){
            return Tool::returnJson([],417,'选择开户行与卡开户行不匹配');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{

            if ($resarr['data']['result'] == '01') {
                $result = $this->WBankAccess->modifyBank($param);
                if(!$result){
                    $transaction->rollBack();
                    return Tool::returnJson([],418,'银行卡信息存储失败');
                }
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson([],200,'修改成功');
            }
            $transaction->rollBack();
            return Tool::returnJson([],419,'你输入的银行信息有误,请重新输入, 错误如：'.$resarr['data']['remark']);
        }catch (\Exception $e){
            $transaction->rollBack();
            return Tool::returnJson([],5000,'修改绑定银行卡失败');
        };
    }

    //获取绑定信息详情
    public function getBankDetail($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,'买手id不能为空');
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,'安全码不能为空');
        }
        if(md5($data['buy_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,'安全码不正确');
        }

        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyer))
        {
            return Tool::returnJson([],405,'买手账号不存在');
        }
        $bank = $this->RBankAccess->getBuyUserBankAccount($data['buy_id']);
        if(empty($bank))
        {
            return Tool::returnJson([],406,'绑定银行卡信息不存在');
        }
        if($bank['buy_id'] != $data['buy_id'])
        {
            return Tool::returnJson([],406,'非本用户提现信息');
        }

        $bank['AliPay'] = isset($bank['AliPay']) ? $bank['AliPay'] : '';
        $bank['aliUrl'] = isset($bank['aliUrl']) ? $bank['aliUrl'] : '';
        $bank['bankCardUrl'] = isset($bank['bankCardUrl']) ? $bank['bankCardUrl'] : '';
        $bank['idCardUrl'] = isset($bank['idCardUrl']) ? $bank['idCardUrl'] : '';
        $bank['id_positive_url'] = isset($bank['id_positive_url']) ? $bank['id_positive_url'] : '';
        $bank['id_verso_url'] = isset($bank['id_verso_url']) ? $bank['id_verso_url'] : '';
        return Tool::returnJson($bank,200,"成功");
    }

    //检验方法
    private function cardAuth($data)
    {
        $apiId = Yii::$app->params['bank_config']['bank_params']['appId'];
        $appKey = Yii::$app->params['bank_config']['bank_params']['appKey'];
        $params = [
            'appId' => $apiId, // appId,登录万数平台查看
            'appKey' => $appKey, // appKey,登录万数平台查看
            'name' => $data['real_name'], // 姓名
            'idNum' => $data['idcard'], // 身份证号码，限单个
            'cardNo' => $data['cardnum'], // 银行卡号，限单个
            'mobile' => $data['bankphone'], // 银行预留手机号码，限单个，仅支持国内11位号码
            'Content-Type'=>'multipart/form-data',
        ];
        //发送验证
        $result = $this->sendAuth($params);
        return $result;
    }

    private function sendAuth($params)
    {
        $url = Yii::$app->params['bank_config']['bank_url'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $result = curl_exec($ch);
        return $result;
    }
}